package org.bluedream.core.module.base;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.shiro.SecurityUtils;
import org.bluedream.comm.utils.EmptyUtil;
import org.bluedream.comm.utils.ReflexUtil;
import org.bluedream.comm.utils.RestResult;
import org.bluedream.core.module.entity.stock.TmpSkuStock;
import org.bluedream.core.module.service.stock.SkuStockService;
import org.bluedream.core.module.service.stock.TmpSkuStockService;
import org.bluedream.core.utils.UserUtil;
import org.bluedream.core.utils.configUtil.GoalConfigUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;


@Transactional(
        readOnly = true
)
public class BillServiceImpl<M extends BaseMapper<T>, T> extends OrgBaseServiceImpl<M , T> {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private SkuStockService skuStockService;
    @Resource
    private TmpSkuStockService tmpSkuStockService;

    public void setCheckAttribute(T entity){
        String loginInfo = (String) SecurityUtils.getSubject().getPrincipal();
        ReflexUtil.setFieldValue(entity , "checkBy" , loginInfo);
        ReflexUtil.setFieldValue(entity , "checkDate" , new Timestamp(System.currentTimeMillis()));
        ReflexUtil.setFieldValue(entity , "status" , "3");
    }

    protected String isCheckSkuQty(String orgCode , String warCode , String productCode , BigDecimal qty , Integer billTypeLabel){
        boolean negativeStockAllow = GoalConfigUtil.getValueByKey("sys.negativeStock.allow").equals("1")?true:false;
        BigDecimal nowSkuQty = skuStockService.getNowSkuStockQty(orgCode , warCode , productCode);
        if (EmptyUtil.isEmpty(nowSkuQty)){
            nowSkuQty = new BigDecimal("0");
        }

        if (EmptyUtil.isEmpty(qty)){
            qty = new BigDecimal("0");
        }

        BigDecimal tmpQty = nowSkuQty.add(qty.multiply(BigDecimal.valueOf(billTypeLabel)));
        String msg = "数据保存失败:商品[" + productCode + "]的实时库存" + nowSkuQty + "小于出库数量，不允许负库存出库操作，请重新确认！";
        if (!negativeStockAllow && billTypeLabel < 0 && tmpQty.compareTo(new BigDecimal("0")) < 0){
            return msg;
        }

        return null;
    }


}
